package com.ztesoft.ip.utils;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.xiaoleilu.hutool.Log;
import com.xiaoleilu.hutool.Setting;
import com.xiaoleilu.hutool.db.ds.DruidDS;

public final class DruidDatasource {
	private static DruidDataSource ds = null;

	private static DruidDataSource getDataSource() {
		if (null == ds || !ds.isEnable())
			initDB();
		return ds;
	}

	public static final DruidPooledConnection getConnection() throws SQLException {
		if (null != ds && ds.isEnable())
			return ds.getConnection();
		else {
			initDB();
			return ds.getConnection();
		}
	}

	public static final void initDB() {
		/*
		 * ds = new DruidDataSource();
		 * ds.setUrl("jdbc:oracle:thin:@192.168.56.101:1521:ORCL");
		 * ds.setUsername("ycsmart4"); ds.setPassword("ycsmart4");
		 */
		// 第一种 druid配置文件不生效
		/*
		 * DruidDS.init(new Setting(new File("resouce/config/druid.setting"),
		 * Setting.DEFAULT_CHARSET, false), new Setting(new
		 * File("resouce/config/db.setting"), Setting.DEFAULT_CHARSET, false));
		 * ds = new DruidDataSource();
		 * ds.setUrl("jdbc:oracle:thin:@192.168.56.101:1521:ORCL");
		 * ds.setUsername("ycsmart4"); ds.setPassword("ycsmart4");
		 */

		// 第二种 数据源获取成功，但是读取表提示表不存在
		DruidDS.init(new Setting(new File("resouce/config/druid.setting"), Setting.DEFAULT_CHARSET, false), new Setting(new File("resouce/config/db.setting"), Setting.DEFAULT_CHARSET, false));
		ds = (DruidDataSource) DruidDS.getDataSource("oracl4old");
		Log.info("数据库连接池初始化成功!初始化连接池大小:" + ds.getInitialSize() + "*" + ds.getUrl());
	}

	public static final void closeDB() {
		if (null != ds && ds.isEnable())
			ds.close();
	}
}
